#include <windows.h>
#include "CNpcPacket.h"
#include "CUtil.h"
#include "math.h"

CNpcPacket::CNpcPacket(CNpc * CEnt, bool tmpDespawn  ) {



	memset(this->data, 0, 0x60);
	this->type = 0x0E;
	this->data[0x0A-4]	= CEnt->type;  //NPC_UPDATE_ALL

	this->m_dontProcessOnZone = 1;

	if(CEnt->type == 0x57 ){
		this->size = 0x28;
		memcpy(this->data+0x30-4, &(CEnt->lookc), 20);
	//	this->data[0x0A-4] ^= 0x10;  // NPC_UPDATE_BIT_4 (Updates NPC looks)
		//memcpy(this->data+0x30+20-4, CEnt->m_name, strlen((const char*)CEnt->m_name));
		this->data[0x0A-4] = 0x57;
	}
	else if(CEnt->type == 0x07 ) {
		this->size = 0x20;
		memcpy(this->data+0x30-4, &(CEnt->look), 4);
		memcpy(this->data+0x34-4, CEnt->m_name, 16);
		if(sizeof(CEnt->m_name) > 8)
			this->size = 0x24;
	}
	else {
		this->size = (unsigned char)((0x33+strlen((const char*)CEnt->m_name)+sizeof(int))/4)*2;
		memcpy(this->data+0x30-4, &(CEnt->look), 4);
		//memcpy(this->data+0x34-4, CEnt->m_name, strlen((const char*)CEnt->m_name));
	}


	this->m_packetIdentifier = CEnt->m_id ;

	memcpy(this->data+4-4, &CEnt->m_id, 4);
	unsigned short targId = CEnt->getTargId();
	memcpy(this->data+8-4, &targId, 2);
	this->data[0x1f-4]  = CEnt->getAnimation();
	this->data[10-4]  = CEnt->type;
	
	this->data[0x1c-4] = CEnt->m_speed;
	this->data[0x1d-4] = CEnt->m_speedAlt;

	this->data[0x1E-4] = (unsigned char) ceil((((float)CEnt->h.hp / (float)CEnt->getMaxHp()))*100);
	
	// controls the name prefix, such as "the" Seeker Bats 0x40 adds "the".
	if((CEnt->status != 0x00) && (CEnt->status != 0x06)) {
		this->data[0x27-4] =  CEnt->m_namePrefix;
	}

	this->data[11-4]   = (unsigned char)CEnt->loc.p.rotation;

	memcpy(this->data+12-4,   &CEnt->loc.p.x , 4);
	memcpy(this->data+16-4,   &CEnt->loc.p.y , 4);
	memcpy(this->data+20-4,   &CEnt->loc.p.z , 4);
	memcpy(this->data+0x18-4, &CEnt->m_walkCnt, 2);
	

	memcpy(this->data+0x2c-4, &CEnt->ownerId, 4);
	if(tmpDespawn) {
		this->data[0x20-4] = 0x07;
	} else {
		memcpy(this->data+0x20-4, &CEnt->status, 1);
	}

	this->data[0x2A-4] = CEnt->m_animationAlt;
	this->data[0x2B-4] = CEnt->namevis;

	memcpy(this->data+0x21-4, &CEnt->unknown, 3);

	if(CEnt->isPet())
		this->data[0x27-0x04] = 0x08;  // Set name color to Teal (pet)

	if(CEnt->isCharSpawned()) {
		this->data[0x28-0x04] |= 0x04;  // Set spawn animation flag on
		//Entity only spawns once
		CEnt->isCharSpawned(false);
	}
}

CNpcPacket::~CNpcPacket() {

}
